/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 * 
 *	Created on 2010-12-30 上午09:10:24
 */
package cn.com.ccxe.core.crawl.article;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.ccxe.core.crawl.ThreadPoolService;
import cn.com.ccxe.core.util.Configurations;

/**
 * 列表处理类
 * @author hetao
 */
public class ArticleService extends Thread {

	 /**
     * 启动列表抓取的线程数
     */
	private static int 				List_PAGE_CRAWLER = Configurations.getInt("article.crawler.amount", 5);
	private ThreadPoolService 		threadPoolService;
	final 	Logger					logger = LoggerFactory.getLogger(ArticleService.class);
	private static AtomicBoolean	shutDown = new AtomicBoolean(true);
	
	public ArticleService(ThreadPoolService threadPoolService) {
		this.threadPoolService = threadPoolService;
	}

	public void run() {
		logger.info(this.getClass().getName()+"启动了.....");
		List<ArticleCrawler> crawlers = createTask();
		threadPoolService.excute(crawlers);
		while (true) {
			try {
				sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			for (ArticleCrawler crawler : crawlers) {
//				logger.info("{} 现处于 {} 状态.....",crawler.name(),crawler.state());
//				crawler.getCrawlerInfo(logger);
				if(!shutDown.get()) {
					crawler.shutDown();
				}
			}
			if(!shutDown.get()) {
				interrupt();
			}
		}
	}
	
	public List<ArticleCrawler> createTask() {
		List<ArticleCrawler> crawlers = new ArrayList<ArticleCrawler>(List_PAGE_CRAWLER);
		for (int i = 0; i < List_PAGE_CRAWLER; i++) {
			crawlers.add(new ArticleCrawler("文章采集器--"+i*111+"--"));
		}
		return crawlers;
	}
	public void shutDown() {
		shutDown.set(false);
		threadPoolService.destoryExecutorService(10000);
	}
	
}
